package com.lty.jeeg.server.modules.tms.service.impl;

import com.lty.jeeg.server.common.page.table.PageTableHandler;
import com.lty.jeeg.server.common.page.table.PageTableRequest;
import com.lty.jeeg.server.common.page.table.PageTableResponse;
import com.lty.jeeg.server.common.utils.UserUtil;
import com.lty.jeeg.server.modules.sys.service.impl.BaseService;
import com.lty.jeeg.server.modules.tms.dao.ProjectDao;
import com.lty.jeeg.server.modules.tms.dao.TaskDao;
import com.lty.jeeg.server.modules.tms.model.Project;
import com.lty.jeeg.server.modules.tms.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author : LTY
 * @date : 2019-03-26 10:52:43
 * Description : 
 */
@Service
@Slf4j
public class ProjectServiceImpl implements ProjectService {

    private final ProjectDao projectDao;

    private final TaskDao taskDao;

    @Autowired
    public ProjectServiceImpl(ProjectDao projectDao, TaskDao taskDao) {
        this.projectDao = projectDao;
        this.taskDao = taskDao;
    }

    @Override
    public Project getById(Long id) {
        return projectDao.getById(id);
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
	public int delete(Long id) {
		log.debug("删除project=>{}", id);
        taskDao.deleteBy(id);
		return projectDao.delete(id);
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
	public int update(Project project) {
	    project.preUpdate();
        log.debug("修改project=>{}", project.getId());
        return projectDao.update(project);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(Project project) {
        project.preInsert();
        if(project.getParentId() !=null){
            project.setIsSubProject("1");
            //修改项目是否有子项目
            Project projectParent = projectDao.getById(project.getParentId());
            projectParent.setIsSubProject("1");
            projectParent.setId(project.getParentId());
            projectDao.update(projectParent);
        }
        projectDao.save(project);
        log.debug("新增project=>{}", project.getId());
        return project.getId();
    }

    @Override
    public PageTableResponse list(PageTableRequest request) {
        request.getParams().put("dsf", BaseService.dataScopeFilter("tms", UserUtil.getCurrentUser(), "d1,d2,d3,d4,d5", "u1,u2,u3,u4,u5"));
        return new PageTableHandler(
                request1 -> projectDao.count(request1.getParams()),
                request2 -> projectDao.list(
                        request2.getParams(), request2.getOffset(), request2.getLimit()))
                .handle(request);
    }



}
